<template>
	<view>
		<view class="top"></view>
		<view class="navibar-and-date">
			<!-- 上方的导航栏，包括设置、学期选择 -->
			<navi-bar
				v-bind:style="{ marginTop: statusBarHeight + 'px', height: '60' + 'rpx' }"></navi-bar>
			<!-- 上方日期栏 -->
			<month-and-weeks :day="day" :week="week" :showingWeek="showingWeek" @animationfinish="changeDateList"></month-and-weeks>
			

		</view>

		<view class="timeline-and-courses" :style="{ paddingTop: 'calc(' + naviBarHeight + 'px' + ' + ' + '175rpx)' }">

			<!-- 左侧竖着的时间栏 -->
			<time-line :each_height="courseRenderConfig.each_height"></time-line>
			
			<!-- 课程展示区域 -->
			<courses :todayDay="day" :today-week="week" :showingWeek="showingWeek" @animationfinish="changeCourseWeek" :naviBarHeight="naviBarHeight"></courses>
			
			
		</view>

	</view>
</template>
<script>
	// import index_module from "../home/login.vue"
	import naviBar from "./components/naviBar.vue"
	import timeLine from './components/timeLine.vue'
	import courses from './components/courses.vue'
	import {
		colors
	} from './color.vue'
	import monthAndWeeks from './components/monthAndWeeks'
	 import test_kechengbiao from './components/test_kechengbiao.json'


	export default {
		components: {
			naviBar,
			monthAndWeeks,
			timeLine,
			courses,
		},
		data() {
			return {
				// 是否给今天加黑色标记
				// isRenderDayColor: true,
				// title: '',
				// year: '',
				// onetoseven: [0, 1, 2, 3, 4, 5, 6],
				// onetotwentyfour: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
				// 	24
				// ],
				showingWeek: 0, //当前正在展示的week
				// startMonday: false,
				// startMondayNot: true,

				// cweekdays: undefined,
				showMask: false,

				// cterm: '',
				// season: '',
				// nseason: '',
				// 从后端获取的原始数据，添加了color的信息
				kechengbiao: [],
				// time_top: 0,
				week: 0, //今天是第几周，从0开始
				day: -1, //今天的星期，从0开始
				// origin_week: undefined,
				// show_event_list: undefined,
				// show_choose: false,
				// show_term: false,
				naviBarHeight: undefined,
				statusBarHeight: undefined,
				add_event: undefined,
				event_list: undefined,
				// choose_week_ani: '',
				// time_counter: undefined,
				courseSchedule: undefined,
				courseRenderConfig: { //单位rpx
					each_height: 112,
					each_width: 93,
					block_width: 85,
					margin_left: 92,
					margin_top: 94,
				},
				// weeks_render_list: undefined, //所有的课程数据，由 calcEventList() 函数计算得到。
				// weeks_time_list: undefined,
				// mask_ani: undefined,
				// show_mask: false,
				// show_day: -1,
				// show_juti: -1,
				// current: 0,
				// month: undefined,
				// newList: [],
				// mineAndOther: [{
				// 		name: '我'
				// 	},
				// 	{
				// 		name: 'Ta'
				// 	},
				// 	{
				// 		name: 'both'
				// 	}
				// ],
				// curNow: 0,
				// yaoqingma: "",
				// mine_list: [],
				// empty_list: [],
				// it_list测试数据
				// it_list: [],

			};
		},
		onLoad() {
			// this.monthAndWeeks = new MonthAndWeeks()
			
			//liang
			// this.startMonday = getApp().globalData.startMonday
			//这里读取是否开启周日
			//不要放到onShow

			this.naviBarHeight = getApp().globalData.naviBarHeight;
			this.statusBarHeight = getApp().globalData.statusBarHeight;
			// var xuehao = getApp().globalData.xuehao


			var today = this.TodayInfo(getApp().globalData.start_date);
			this.day = today.day - 1; //今天星期几，从0开始
			this.week = today.week - 1; //今天是开学第几周，从0开始
			// this.day=2
			// this.week=0
			console.log('today:', 'week', this.week, 'day', this.day)
			if (this.week < 0) {
				this.showingWeek = 0
			} else if (this.week > 23) {
				this.showingWeek = 23
			} else {
				this.showingWeek = this.week
			}
			// 无后端时，测试使用
			 getApp().globalData.kechengbiao = test_kechengbiao //用于测试的课程表

		},
		onShow() {

			// 获取课程表
			var that = this
			this.kechengbiao = getApp().globalData.kechengbiao;
			//若为空，重新获取
			if (JSON.stringify(this.kechengbiao) == "[]" || this.kechengbiao == undefined || this.kechengbiao == null) {
				console.log("课程表为空,重新获取课表")
				uni.showLoading({
					title: "获取课表中..."
				})
				getClassTable(
					()=>{
						uni.hideLoading()
						uni.showToast({
							title: "获取课表成功",
							duration: 500,
						})
					},
					()=> {
						uni.hideLoading()
						uni.showToast({
							title: "获取课表失败",
							duration: 500,
						})
					},
					()=>{
						uni.hideLoading()
					})
			}

			//liang
			// this.startMonday = getApp().globalData.startMonday
			//这里读取是否开启周日

			// this.weekdays = this.startMonday ? ['日', '一', '二', '三', '四', '五', '六'] : ['一', '二', '三', '四', '五', '六', '日'];
			// kechengbiao用于储存官方获取到的课程，add_event用于储存用户自定义添加的课程，但目前没有区分，全都在课程表内
			


			// console.log(this.courseSchedule)
			// console.log(this.courseSchedule.getCourseList())
			// console.log(this.courseSchedule.getCourseList()[0])
			// var today = this.TodayInfo(getApp().globalData.start_date);
			// var day = today.day;
			// var week = today.week;
			// if (week >= 1) {
			// 	if (week > 23) {
			// 		this.week = 24;
			// 		console.log('现在已经放假');
			// 		this.day = -1
			// 	} else {
			// 		this.week = today.week - 1;
			// 		console.log('现在是开学第' + today.week + '周' + today.day);
			// 		this.day = day - 1
			// 		if (this.day < 0) {
			// 			this.day = 6
			// 		}
			// 	}

			// } else {
			// 	this.week = 0
			// 	this.day = -1
			// 	console.log('现在还未开学')
			// }
			// this.current = this.week;
			// // 若有课程，则计算课程样式
			// if (this.event_list.length) {
			// 	this.calcEventList();
			// }
			// this.calcDate();
			// this.startMondayNot = false;

		},
		methods: {
			
			changeDateList(e) {
				this.showingWeek = e.current
			},
			changeCourseWeek(e) {
				this.showingWeek = e.current
			},
			TodayInfo(start) {
				// 计算今天到输入日期的差别周数，返回weekInfo，其中weekInfo.day表示今天是周几，weekInfo.week表示与目标日期以来的周数，week为1表示处于第一周。
				var WEEKLEN = 7, // 一周7天为常量
					WEEKDAYS = ['日', '一', '二', '三', '四', '五', '六'],
					weekInfo = {
						week: null,
						day: null
					}, // 初始化返回信息，默认第null周，星期null
					oneDay = 24 * 60 * 60 * 1000, // 一天的毫秒时长
					weekLeave, // 开学当天所在周剩余天数
					weekStart, // 开学当天start是星期几
					today, // 今天
					dateDiff, // 今天与开学当天日期差
					sDate; //开学之日，日期对象
				var rDateStr = /\d{4}[\/-]\d{1,2}[\/-]\d{1,2}/g; // 简单的日期格式校验：2013/12/19
				if (!rDateStr.test(start)) {
					console.log('请使用合法的开学日期！！！');
					return weekInfo;
				}
				sDate = new Date(start.replace('-', '/').replace('-', '/'));
				// console.log(sDate);
				weekStart = sDate.getDay();
				weekStart = weekStart === 0 ? 7 : weekStart; // JS中周日的索引为0，这里转换为7，方便计算
				weekLeave = WEEKLEN - weekStart;
				today = new Date();
				// console.log(today)
				weekInfo.day = today.getDay();
				weekInfo.day = this.startMonday ? (weekInfo.day == 6 ? 0 : today.getDay() + 1) : weekInfo.day;
				today = new Date(today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate());
				dateDiff = today - sDate;
				dateDiff = parseInt(dateDiff / oneDay);
				weekInfo.week = Math.ceil((dateDiff - weekLeave) / WEEKLEN) + 1;
				if (this.startMonday && weekInfo.day == 1) {
					weekInfo.week += 1
				}
				// console.log(1111);
				// console.log(weekInfo);
				return weekInfo;
			},
			
			
			// changeOverlap(index, current) {
			// 	// 处理展开后的点击事件。（重叠课程未展开前不可操作）
			// 	var id = this.weeks_render_list[current][index].id
			// 	getApp().globalData.current_event_index = id
			// 	getApp().globalData.event = this.kechengbiao[id]
			// 	getApp().globalData.change_kechengbiao = 1
			// 	uni.navigateTo({
			// 		url: 'change'
			// 	})
			// },
			confirmWeek(e) {

				this.week = e[0].value;
				console.log(this.week);
				this.calcEventList();
				this.calcDate();

				// this.current = e[0].value;
				// this.week = e[0].value;
				// this.calcEventList();
				// this.calcDate();

			},
			// 改变学期
			confirmTerm(e) {
				this.cterm = e[0].label;
				this.season = e[1].label;
				console.log(this.cterm);
				if (this.season == "春季") {
					this.nseason = 1
				} else {
					this.nseason = 2
				}
				console.log(this.nseason);
				this.title = this.cterm + '--' + this.season;
				console.log(this.cterm - 1980)

				this.refresh()

			},
			refresh(e) {
				var that = this;
				uni.showLoading({
					title: "加载中"
				})
				uni.request({
					url: getApp().globalData.URL + "common_apis/get_kechengbiao",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						username: getApp().globalData.username,
						userpassword: getApp().globalData.userpassword,
						year: that.cterm - 1980,
						term: that.nseason

					},
					success(res) {
						console.log("kechengbiao:", res);
						if (res.data.statusCode == 1000) {
							that.newList = res.data.kechengbiao


							console.log(that.newList)
							if (res.data.kechengbiao.length == 0) {
								uni.showToast({
									title: "该学期无课表",
									icon: 'none',
								})
							} else {

								for (var i = 0; i < that.newList.length; i++) {
									that.newList[i].id = i
									that.newList[i].color = {
										id: 3,
										name: '蓝色',
										border_color: '#51aaf2',
										background_color: '#d6edfb',
										font_color: '#2f6691',
										fill_color: '#59b0f3',
										checked: false
									}
								}
								that.event_list = that.newList
								that.calcEventList();
								uni.showToast({
									title: "正在获取课表",
									icon: 'none',
								})
							}

						} else {
							uni.showToast({
								title: "未获取到课表",
								icon: 'none'
							})
						}
					},
					fail(res) {
						console.log(res);
						uni.showToast({
							title: '路由失败',
							icon: 'none'
						})
					},
					complete() {
						uni.hideLoading();
					}
				})


			},




			sectionTurn(index) {
				this.curNow = index;
				console.log(index)
				if (index == 0) {
					this.event_list = this.mine_list;
					this.calcEventList()

				}
				if (index == 1) {
					console.log("other class 11");
					this.it_list = uni.getStorageSync("otherclass")

					console.log(this.it_list);


					this.event_list = this.it_list;

					this.calcEventList()
				}
				if (index == 2) {
					var a = this.mine_list
					var b = this.it_list
					var bothClass = a.concat(b)
					console.log(bothClass);
					this.event_list = bothClass
					this.calcEventList();
					uni.showToast({
						title: '和Ta一起努力吧',
						icon: 'none',
						duration: 2000
					})


				}
				// 多人空课表就交给小可爱你们了


				// if (index == 3) {

				// 	let i
				// 	let j
				// 	let k

				// 	// mine
				// 	let emptyOwner = []
				// 	for (i = 0; i < 24; i++) {
				// 		emptyOwner.push([])
				// 		for (j = 0; j < 7; j++) {
				// 			emptyOwner[i].push([])
				// 			for (k = 0; k < 12; k++) {
				// 				emptyOwner[i][j].push([])
				// 				emptyOwner[i][j][k] = 0
				// 			}
				// 		}
				// 	}
				// 	console.log("emptyOwner:", emptyOwner);
				// 	let ownerList = emptyOwner

				// 	for (let index = 0; index < this.mine_list.length; index++) {
				// 		for (let indexTime = 0; indexTime < this.mine_list[index].time.length; indexTime++) {
				// 			for (i = 0; i < this.mine_list[index].time[indexTime].week; i++) {
				// 				for (j = 0; j < this.mine_list[index].time[indexTime].juti.length; j++) {
				// 					ownerList[this.mine_list[index].time[indexTime].week[i]][owner[index].time[indexTime]
				// 						.day
				// 					][owner[index].time[indexTime].week[j]] = 1
				// 				}
				// 			}
				// 		}
				// 	}
				// 	console.log("ownerList:", ownerList);


				// 	// other
				// 	let emptyOther = []
				// 	for (i = 0; i < 24; i++) {
				// 		emptyOther.push([])
				// 		for (j = 0; j < 7; j++) {
				// 			emptyOther[i].push([])
				// 			for (k = 0; k < 12; k++) {
				// 				emptyOther[i][j].push([])
				// 				emptyOther[i][j][k] = 0
				// 			}
				// 		}
				// 	}
				// 	console.log("emptyOther:", emptyOther);
				// 	let otherList = emptyOther
				// 	for (let i = 0; i < this.it_list.length; i++) {
				// 		for (let j = 0; j < this.it_list[i].time.length; j++) {
				// 			for (let k = 0; k < this.it_list[i].time[j].week.length; k++) {
				// 				for (let m = 0; m < this.it_list[i].time[j].juti.length; m++) {
				// 					otherList[this.it_list[i].time[j].week[k]][this.it_list[i].time[j].day][this.it_list[i]
				// 						.time[j].juti[m]
				// 					] = 1
				// 				}
				// 			}
				// 		}
				// 	}

				// 	console.log("otherList:", otherList);
				// 	// 再建一个空数组  后续可思考简便方法
				// 	var both_empty_box = []
				// 	for (let i = 0; i < 24; i++) {
				// 		both_empty_box.push([])
				// 		for (let j = 0; j < 7; j++) {
				// 			both_empty_box[i].push([])
				// 			for (let k = 0; k < 12; k++) {
				// 				both_empty_box[i][j].push([])
				// 				both_empty_box[i][j][k] = 0
				// 			}
				// 		}
				// 	}
				// 	for (let i = 0; i < 24; i++) {

				// 		for (let j = 0; j < 7; j++) {

				// 			for (let k = 0; k < 12; k++) {
				// 				both_empty_box[i][j][k] = otherList[i][j][k] || ownerList[i][j][k]
				// 			}
				// 		}
				// 	}


				// 	console.log("both");
				// 	console.log(both_empty_box);

				// }

			}
		}
	}
	// 获取课程表,并保存在全局变量和缓存中
	export function getClassTable(success_callback, fail_callback, complete_callback) {
		var username = getApp().globalData.username
		var password = getApp().globalData.userpassword
		if (!username || !password) {
			wx.showToast({
				title: '未能获取课程表，请到“我的”页面重新登录',
				icon: 'none',
				duration: 2000
			});
			// return []
		}
		console.log("向后端获取课表中...")
		var that = this
		uni.request({
			url: getApp().globalData.BACK + 'core/classtable',
			data: {
				username: username,
				password: password,
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			method: 'POST',
			fail(res) {
				console.log('获取课程表失败', res)
				if(fail_callback){
					fail_callback(res)		
				}
			},
			success(res) {
				if(res.statusCode!=500){
					console.log(res)
					var kechengbiao = res.data.data;
					console.log("获取课程表成功", res.data.data)
					for (var i = 0; i < kechengbiao.length; i++) {//随机分配颜色
						let num_colors = colors.length
						let choice = Math.floor(Math.random() * num_colors) // [0,num_colors）区间内的整数
						kechengbiao[i].color = colors[choice]
						kechengbiao[i].uid = i
					}
					getApp().globalData.kechengbiao = kechengbiao;
					uni.setStorageSync('kechengbiao', kechengbiao);
					
					if (getApp().globalData.platform == 'ios') {
						//ios专属，不知道干嘛用的
						iosClassTableAdd()
					}
					if(success_callback){
						success_callback(kechengbiao)
					}
				}
			},
			complete(res) {
				if(complete_callback){
					complete_callback(res)		
				}
			},
		});
		
	}


	//ios专属课程表？不知道干嘛用的
	export function iosClassTableAdd() {
		var UserDefaultsClass = plus.ios.importClass(
			'NSUserDefaults');
		var standardUserDefaults = UserDefaultsClass
			.standardUserDefaults().initWithSuiteName(
				'group.cyonline.makeabetterworld.cn');
		plus.ios.invoke(
			standardUserDefaults,
			'setObject:forKey:',
			JSON.stringify(getApp().globalData.kechengbiao
				.concat(getApp().globalData.add_event)),
			'kechengbiao'
		);
		// plus.ios.invoke(standardUserDefaults, 'synchronize');
		// 在更改的地方重复

		var xuehao = getApp().globalData.xuehao
		xuehao = Number(xuehao[3] + xuehao[4])
		var date = new Date()
		const now = date.getFullYear()
		var diff = now - 2000 - xuehao
		console.log(xuehao)
		console.log(now);
		console.log(diff);
		var begintime = ['08:30', '09:25', '10:30', '11:25',
			'14:30', '15:25', '16:30', '17:25', '19:00',
			'19:55', '20:50', '21:45'
		]
		var endtime = ['09:15', '10:10', '11:15', '12:10',
			'15:15', '16:10', '17:15', '18:10', '19:45',
			'20:40', '21:35', '22:30'
		]
		console.log(begintime)
		console.log(endtime)
		plus.ios.invoke(
			standardUserDefaults,
			'setObject:forKey:',
			JSON.stringify(begintime),
			'beginTime'
		);
		plus.ios.invoke(
			standardUserDefaults,
			'setObject:forKey:',
			JSON.stringify(endtime),
			'endTime'
		);
		plus.ios.invoke(standardUserDefaults, 'synchronize');
		console.log(plus.ios.invoke(standardUserDefaults,
			'objectForKey:', 'beginTime'));
		console.log(plus.ios.invoke(standardUserDefaults,
			'objectForKey:', 'endTime'));
	}
</script>
<style>
	.top{
		width: 100vw;
		height: 100rpx;
		background: white;
	}
	.navibar-and-date {
		width: 100vw;
		background-color: #f7f7f7;
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		flex-direction: column;
		z-index: 102;
	}

	.timeline-and-courses {
		width: 100vw;
		background-color: #fff;
		display: flex;
		flex-direction: row;
		overflow: hidden;
		position: relative;
		width: 750rpx;
	}

	/*month and weeks start*/
	.flex-row-container {
		display: flex;
		flex-direction: row;
		margin-top: 16rpx;
		height: 52rpx;
	}

	.flex-column-container {
		display: flex;
		flex-direction: column;
		width: 92rpx;
		align-items: center;
		position: relative;
		height: 52rpx;
	}

	.month-weeks-row-container {
		display: flex;
		flex-direction: row;
		height: 100rpx;
		margin-bottom: 8rpx;
	}

	.show-month-box {
		width: 92rpx;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
	}

	.show-month-circle-text {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 80rpx;
		height: 80rpx;
		background-color: #3478f6;
		border-radius: 92rpx;
	}

	.flex-column-inner-container {
		display: flex;
		flex-direction: column;
		width: 93rpx;
		align-items: center;
		position: relative;
		height: 52rpx;
		justify-content: space-between;
	}

	.styled-text {
		font-size: 24rpx;
		padding-bottom: 5rpx;
		height: 52rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.date-swiper {
		width: 651rpx;
		height: 100rpx;
		background-color: #d1d1d8;
		border-radius: 100rpx;
		margin-right: 7rpx;
		overflow: hidden;
		z-index: 103;
	}

	.date-in-week {
		width: 93rpx;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 103;
	}



	.date-item {
		font-size: 32rpx;
		width: 80rpx;
		height: 80rpx;
		background-color: #000;
		border-radius: 93rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
	}

	.chooseWeek {
		z-index: 1044;
		position: absolute;
		left: 0;
		top: 0;
		background-color: #fff;
		color: #000;
		width: 100%;
		height: 100%;
		opacity: 0;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		/* animationmation: stop 0.4s forwards;
		display: flex;flex-direction: row;z-index:103; */
	}

	.week-name {
		align-items: center;
		align-self: center;
		display: flex;
		flex-direction: row;
		overflow: hidden;
	}

	/* 控制显示周次的动画 */
	/* .start_choose_week {
		animationmation: start 0.2s forwards;
	}
	@keyframes stop {
		0% {
			opacity: 1;
		}

		100% {
			opacity: 0;
		}
	}

	@keyframes start {
		0% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	} */
	/* month and weeks end */
	

	.topic_cont_text {
		overflow: hidden;
		word-break: break-all;
		/* break-all(允许在单词内换行。) */
		text-overflow: ellipsis;
		/* 超出部分省略号 */
		display: -webkit-box;
		/** 对象作为伸缩盒子模型显示 **/
		-webkit-box-orient: vertical;
		/** 设置或检索伸缩盒对象的子元素的排列方式 **/
		-webkit-line-clamp: 3;
		/** 显示的行数 **/
	}

	body {
		font-family: 'pingfang';
	}
</style>